import axios from 'axios'
import store from '@/store'
import router from '@/router'
import { Toast } from 'vant'
const instance = axios.create({
  baseURL: 'http://toutiao.itheima.net',
  // 设置超时时间
  timeout: 5000
})
// 添加请求拦截器
instance.interceptors.request.use(
  function (config) {
    // 在发送请求之前做什么
    // console.log(config)
    const token = store.state.user.token.token

    if (token) {
      config.headers.Authorization = 'Bearer ' + token
    }
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)
function goLogin() {
  store.commit('user/removeToken')
  Toast('登录过期，请重新登录')
  router.push({
    path: '/login',
    back: router.currentRoute.fullPath
  })
}

// 添加响应拦截器
instance.interceptors.response.use(
  function (response) {
    // 对响应数据做点什么
    return response.data
  },
  async function (error) {
    console.log(error)
    // 对响应错误做点什么
    const refreshToken = store.state.user.token.refresh_token
    if (error.response.status === 401) {
      if (refreshToken) {
        try {
          const res = await axios({
            url: 'http://toutiao.itheima.net/v1_0/authorizations',
            method: 'PUT',
            headers: {
              Authorization: `Bearer ${refreshToken}`
            }
          })
          store.commit('user/setToken', {
            token: res.data.data.token,
            refresh_token: refreshToken
          })
          return instance(error.config)
        } catch {
          goLogin()
        }
      } else {
        goLogin()
      }
    }
    return Promise.reject(error)
  }
)
export default instance
